package com.weifei.core.mvc;

import com.weifei.core.anotation.WFRequestParam;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

public class DispatcherHandler {

    private Object controller;
    private Method method;
    private Pattern pattern; // 正则表达式,保存URL
    private Map<String, Map<String, Object>> paramMapping;

    public DispatcherHandler(){}

    public DispatcherHandler(Object controller, Method method, Pattern pattern) throws InstantiationException, IllegalAccessException {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        this.paramMapping = new ConcurrentHashMap<>();

        this.putParamMapping(method);
    }

    public Pattern getPattern() {
        return pattern;
    }

    private void putParamMapping(Method method) throws IllegalAccessException, InstantiationException {
        Parameter[] parameters = method.getParameters();
        for (int i=0;i<parameters.length;i++) {
            String paramName = parameters[i].getName();
            if (parameters[i].isAnnotationPresent(WFRequestParam.class)) {
                WFRequestParam param = parameters[i].getAnnotation(WFRequestParam.class);
                paramName = param.value();
            }
            Class paramType = parameters[i].getType();
            Map<String, Object> map = new HashMap<>();
            map.put("paramIndex", i);
            map.put("paramType",paramType);
            paramMapping.put(paramName, map);

        }

    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        this.controller = controller;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map<String, Map<String, Object>> getParamMapping() {
        return paramMapping;
    }

    public void setParamMapping(Map<String, Map<String, Object>> paramMapping) {
        this.paramMapping = paramMapping;
    }
    public Object methodInvoke(Object[] paramters) throws InvocationTargetException, IllegalAccessException {
        return this.method.invoke(this.controller, paramters);
    }
}
